package offer.linkedList;

/**
 * @author DengYuan2
 * @create 2021-02-24 19:56
 */
public class n_52 {
    public static void main(String[] args) {
        n_52 n = new n_52();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);
        n1.next = n2;
        n2.next = n3;
        n3.next=n6;
        n4.next = n5;
        n5.next=n6;
        n6.next = n7;
        ListNode res = n.FindFirstCommonNode(n1, n4);
        System.out.println(res);

    }

    /**
     * 大神
     * @param pHead1
     * @param pHead2
     * @return
     */
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        while (p1!=p2) {
            //这样写，p1才有可能是null
            p1 = p1 == null ? pHead2 : p1.next;
            p2 = p2 == null ? pHead1 : p2.next;
        }
        return p1;
    }
}
